
from flask import Blueprint, request, jsonify
from dao.baby_dao import insert_baby, select_all_babies, select_babies_by_condition, update_baby, delete_baby, \
    select_all_baby_names
from util.file_util import saveBase64DataToImageFIle
from util.resp import APIResponse

baby_blueprint = Blueprint('baby', __name__)


# 插入新增宝宝
@baby_blueprint.route('/add', methods=['POST'])
def add_baby():
    data = request.json
    print(data)
    name = data.get('name')  # 获取名字
    nickname = data.get('nickname')  # 获取昵称
    image_base64 = data.get('image')  # 获取base64编码的图片数据
    age = data.get('age')  # 获取年龄
    image = saveBase64DataToImageFIle(image_base64)
    insert_baby(name, nickname, age, image)
    return APIResponse.ok()


# 查询所有宝宝信息
@baby_blueprint.route('/all', methods=['GET'])
def get_all_babies():
    babies = select_all_babies()
    return APIResponse.ok(data=babies)


# 查询所有宝宝名字
@baby_blueprint.route('/all_names', methods=['GET'])
def get_all_baby_names():
    baby_names = select_all_baby_names()
    return APIResponse.ok(data=baby_names)


# 根据条件查询宝宝信息
@baby_blueprint.route('/info/<id>', methods=['GET'])
def get_babies_by_condition(id):
    babies = select_babies_by_condition(id)
    return APIResponse.ok(data=babies)


# 更新宝宝信息
@baby_blueprint.route('/update', methods=['PUT'])
def update_existing_baby():
    data = request.json
    baby_id = data.get('id')
    name = data.get('name')
    age = data.get('age')
    nickname = data.get('nickname')
    image=data.get('image')

    if image is not None:
        image = saveBase64DataToImageFIle(image)
    update_baby(baby_id, name, age, nickname, image)
    return APIResponse.ok()


# 删除宝宝信息
@baby_blueprint.route('/delete/<int:id>', methods=['DELETE'])
def delete_existing_baby(id):
    delete_baby(id)
    return APIResponse.ok()
